<template>
	<view>
		<wd-message-box />
		<wd-toast />
		<wd-search v-model="value" @search="search" hide-cancel placeholder-left placeholder="请输入关键字">
			<template #prefix>
				<wd-popover mode="menu" :content="menu" @menuclick="changeSearchType">
					<view class="search-type">
						<text>{{ searchType }}</text>
						<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
					</view>
				</wd-popover>
			</template>
		</wd-search>

		<wd-table :data="list" :height="600" :border="false" @row-click="handleClick">
			<!-- 表格列定义 -->
			<wd-table-col v-for="(col, index) in columns" :key="index" :prop="col.prop" :label="col.label"
				:width="col.width || '60'" :align="col.align || 'center'">
				<template #value="{ row }">
					<template v-if="col.isTag">
						<wd-tag custom-class="space" :type="col.color ? col.color(row[col.prop]) : 'primary'">
							{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
						</wd-tag>
					</template>
					<template v-else>
						{{ row[col.prop] || '-' }}
					</template>
				</template>
			</wd-table-col>
			<wd-table-col prop="grade" label="操作" width="200" fixed align="left">
				<template #value="{ row }">
					<text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
						查看
					</text>
					<text class="px-1 text-#4d80f0" v-if="row.status === 3"
						@click.stop="row.status === 3  ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
						{{ row.status === 0 ? '修改' :  row.status === 3 ? '重新填写' : ''
						}}
					</text>
					<text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
						{{ row.status === 0 ? '取消' : '' }}
					</text>
					<text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
						{{ row.status !== 2 && row.status !== 4 ? '催办' : '' }}
					</text>
				</template>
			</wd-table-col>
		</wd-table>

		<!-- 分页组件 -->
		<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
			@update:pageNo="changePage" />
		<view class="mx-12 my-8 ">
			<up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"></up-button>
		</view>


	</view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import { OfficeRequisitionApi, OfficeRequisitionVO } from '@/api/oa/officesuppliesreceived'
import * as UserApi from '@/api/system/user'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import Pagination from '@/components/pagination/index.vue'
import { useMessage, useToast } from 'wot-design-uni'
import { expediting } from '@/utils/processinstance'


const message = useMessage()
const toast = useToast()

const userOptions = ref<any>([])
// 确保列配置的 prop 唯一性
const columns = [
	{ prop: 'userName', label: '领用人', width: 160 },
	// { prop: 'storeroomKeeper', label: '库房管理员', width: 120 },
	// { prop: 'purchasingManager', label: '采购员', width: 100 },
	{
		prop: 'status',
		label: '审批状态',
		align: 'center',
		width: 80,
		format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
		color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
		isTag: true
	}
] as any
// 响应式数据
const list = ref<OfficeRequisitionVO[]>([])
const queryParams = ref<any>({
	pageNo: 1,
	pageSize: 10,
	title: undefined,
	type: undefined,
})
const total = ref(0)
const loading = ref(false)

const userList = ref<any[]>([])
const searchType = ref<string>('领用人')
const value = ref<string>('')
const menu = ref<any[]>([
	{
		content: '领用人',
		prop: 'userName'
	},
	{
		content: '采购员',
		prop: 'purchasingManager'
	}
])
function changeSearchType({ item }: { item: any }) {
	searchType.value = item?.content
}
const search = () => {
	// 找到选中的搜索字段
	const selectedMenu = menu.value.find(item => item.content === searchType.value);
	if (selectedMenu) {
		// 清空之前的搜索条件
		queryParams.value.userName = undefined;
		queryParams.value.purchasingManager = undefined;
		// 根据选中的搜索类型设置搜索值
		queryParams.value[selectedMenu.prop] = value.value;
		// 重新获取数据
		fetchList();
	}
};

const getDict = (type: any, value: any) => {
	const dicts = getIntDictOptions(type)
	const dict = dicts.find(item => item.value === value)
	return dict ? dict.label : '待审批'
}
// 切换分页
const changePage = (newPage: any) => {
	queryParams.value.pageNo = newPage
	fetchList()
}
function handleSubmit() {
	fetchList()
}
// 获取物品列表
const fetchList = async () => {
	loading.value = true
	try {
		const response = await await OfficeRequisitionApi.getOfficeRequisitionPage(queryParams.value)
		list.value = response.list
		total.value = response.total
		for (let item of list.value) {
			item.status = item.isApproved === false ? 0 : item.status;
		}
	} catch (error) {
		console.error(error)
	} finally {
		loading.value = false
	}
}
/** 审批进度 */
const handleProcessDetail = (row: any) => {
	const url = `/pagesPackage/OAsystemAutomation/officesuppliesreceived/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`;
	uni.navigateTo({
		url: url
	});
}
/** 点击一整行跳转至详情页面 */
const handleClick = ({ rowIndex }: any) => {
	handleProcessDetail(list.value[rowIndex])

}
/** 新增页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
	let url = `/pagesPackage/OAsystemAutomation/officesuppliesreceived/create`; // 默认新增页面
	// 如果 id 存在，拼接 id 作为参数
	if (id) {
		if (resubmit === true) {
			url += `?id=${id}&resubmit=1`;
		}
		console.log('传过来的Id', id);
		url += `?id=${id}&resubmit=0`;
	} else {
		url += `?resubmit=0`;
	}
	uni.navigateTo({ url });
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		// 发起删除
		await OfficeRequisitionApi.deleteOfficeRequisition(id)
		// 显示成功提示
		toast.success('取消成功')
		// 刷新列表
		await fetchList()
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
const handleExpedite = (row: any) => {
	expediting({
		processInstanceId: row.processInstanceId,
		processName: '青运-办公系统自动化-物品领用'
	})
}
/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userOptions.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
// 生命周期
onMounted(() => {
	fetchList()
	getUserList()
})
onShow(() => {
	fetchList()
})
</script>

<style scoped lang="scss">
.container {
	padding: 20px 10px;
}

.search-type {
	position: relative;
	height: 30px;
	line-height: 30px;
	padding: 0 8px 0 16px;
}

.search-type::after {
	position: absolute;
	content: '';
	width: 1px;
	right: 0;
	top: 5px;
	bottom: 5px;
	background: rgba(0, 0, 0, 0.25);
}

.search-type {
	:deep(.icon-arrow) {
		display: inline-block;
		font-size: 20px;
		vertical-align: middle;
	}
}
</style>